import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { gsap } from 'gsap';
import { useAuth } from '../contexts/AuthContext';
import './Sidebar.css';

const Sidebar: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // Refs for GSAP animations
  const sidebarRef = useRef<HTMLElement>(null);
  const logoRef = useRef<HTMLDivElement>(null);
  const navItemsRef = useRef<HTMLButtonElement[]>([]);
  const bottomSectionRef = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  // Mobile state
  const [isMobile, setIsMobile] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  
  // Auth state
  const { isAuthenticated, userPhone, logout, setShowLoginModal } = useAuth();
  
  // 根据当前路由设置默认激活项
  const getActiveItem = () => {
    const path = location.pathname;
    if (path === '/') return 'inspiration';
    if (path === '/generate') return 'generate';
    if (path === '/edit') return 'edit';
    if (path === '/gallery') return 'gallery';
    if (path === '/history') return 'history';
    return 'inspiration';
  };

  const [activeItem, setActiveItem] = useState(getActiveItem());

  const menuItems = [
    { 
      id: 'inspiration', 
      icon: (
        <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
          <g>
            <path data-follow-fill="currentColor" d="M9.343 2.524a4 4 0 0 1 5.17-.122l.144.122 6 5.333A4.002 4.002 0 0 1 22 10.847V19.5a3 3 0 0 1-3 3h-3.5a2 2 0 0 1-2-2v-3a1.5 1.5 0 0 0-3 0v3a2 2 0 0 1-2 2H5a3 3 0 0 1-3-3v-8.653c0-1.07.43-2.094 1.187-2.843l.156-.147 6-5.333Z" fill="currentColor"></path>
          </g>
        </svg>
      ), 
      label: '灵感', 
      path: '/' 
    },
    { 
      id: 'generate', 
      icon: (
        <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
          <g>
            <path data-follow-fill="currentColor" d="m12 4.046-.5.985a14.727 14.727 0 0 1-6.47 6.47L4.047 12l.985.5a14.728 14.728 0 0 1 6.47 6.47l.5.984.499-.985a14.727 14.727 0 0 1 6.47-6.47l.984-.499-.985-.5a14.727 14.727 0 0 1-6.47-6.47l-.5-.983Zm1.338-1.784c-.556-1.095-2.12-1.095-2.676 0l-.945 1.864a12.727 12.727 0 0 1-5.591 5.59l-1.864.946c-1.095.556-1.095 2.12 0 2.676l1.864.945a12.727 12.727 0 0 1 5.59 5.591l.946 1.864c.556 1.095 2.12 1.095 2.676 0l.945-1.864a12.728 12.728 0 0 1 5.591-5.59l1.864-.946c1.095-.556 1.095-2.12 0-2.676l-1.864-.945a12.728 12.728 0 0 1-5.59-5.591l-.946-1.864Z" clipRule="evenodd" fillRule="evenodd" fill="currentColor"></path>
          </g>
        </svg>
      ), 
      label: '生成', 
      path: '/generate' 
    },
    // { 
    //   id: 'edit', 
    //   icon: (
    //     <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
    //       <g>
    //         <path data-follow-fill="currentColor" d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"></path>
    //       </g>
    //     </svg>
    //   ), 
    //   label: '编辑', 
    //   path: '/edit' 
    // },
    { 
      id: 'gallery', 
      icon: (
        <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
          <g>
            <path data-follow-fill="currentColor" d="M6.938 3.125a1 1 0 0 1 1 1v1.813h8.125V4.125a1 1 0 1 1 2 0v1.813h1.812a1 1 0 1 1 0 2h-1.813v2.937a1 1 0 1 1-2 0V7.937H7.938v8.125h2.938a1 1 0 1 1 0 2H7.937v1.813a1 1 0 1 1-2 0v-1.813H4.125a1 1 0 1 1 0-2h1.813V7.938H4.125a1 1 0 0 1 0-2h1.813V4.125a1 1 0 0 1 1-1Zm10.518 17.363.208-.477a3.68 3.68 0 0 1 1.871-1.898l.641-.285a.447.447 0 0 0 0-.812l-.605-.27a3.682 3.682 0 0 1-1.898-1.961l-.213-.515a.427.427 0 0 0-.794 0l-.214.515a3.682 3.682 0 0 1-1.898 1.962l-.605.269a.447.447 0 0 0 0 .812l.64.285a3.675 3.675 0 0 1 1.872 1.898l.208.477c.152.35.635.35.787 0Z" clipRule="evenodd" fillRule="evenodd" fill="currentColor"></path>
          </g>
        </svg>
      ), 
      label: '画布', 
      path: '/gallery' 
    },
    { 
      id: 'history', 
      icon: (
        <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
          <g>
            <path data-follow-fill="currentColor" d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z" fill="currentColor"></path>
          </g>
        </svg>
      ), 
      label: '历史', 
      path: '/history' 
    }
  ];

  const handleItemClick = (item: any) => {
    setActiveItem(item.id);
    navigate(item.path);
    // 移动端点击后关闭下拉菜单
    if (isMobile) {
      setIsDropdownOpen(false);
    }
  };

  const toggleDropdown = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };

  // 检测移动端
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // 监听路由变化，更新激活状态
  useEffect(() => {
    setActiveItem(getActiveItem());
  }, [location.pathname]);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    if (isDropdownOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isDropdownOpen]);

  // GSAP 入场动画
  useEffect(() => {
    const tl = gsap.timeline();
    
    // 设置初始状态
    gsap.set(sidebarRef.current, { x: -80, opacity: 0 });
    gsap.set(logoRef.current, { y: -20, opacity: 0 });
    gsap.set(navItemsRef.current, { y: 20, opacity: 0 });
    gsap.set(bottomSectionRef.current, { y: 20, opacity: 0 });

    // 执行动画序列
    tl.to(sidebarRef.current, {
      x: 0,
      opacity: 1,
      duration: 0.6,
      ease: "power2.out"
    })
    .to(logoRef.current, {
      y: 0,
      opacity: 1,
      duration: 0.4,
      ease: "back.out(1.7)"
    }, "-=0.3")
    .to(navItemsRef.current, {
      y: 0,
      opacity: 1,
      duration: 0.4,
      stagger: 0.1,
      ease: "power2.out"
    }, "-=0.2")
    .to(bottomSectionRef.current, {
      y: 0,
      opacity: 1,
      duration: 0.4,
      ease: "power2.out"
    }, "-=0.1");

    return () => {
      tl.kill();
    };
  }, []);

  return (
    <>
      <aside ref={sidebarRef} className={`sidebar ${isMobile ? 'mobile' : ''}`}>
        <div className="sidebar-content">
          {/* Logo - Desktop Only */}
          {!isMobile && (
            <div ref={logoRef} className="logo">
              <div className="logo-icon">⭐</div>
            </div>
          )}

          {/* Mobile Dropdown Toggle - Replace Logo */}
          {isMobile && (
            <button className="mobile-menu-toggle" onClick={toggleDropdown}>
              <span className="nav-icon">
                <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
                  <g>
                    <path data-follow-fill="currentColor" d="M3 12h18M3 6h18M3 18h18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"></path>
                  </g>
                </svg>
              </span>
            </button>
          )}

          {/* Desktop Navigation Menu */}
          {!isMobile && (
            <nav className="sidebar-nav">
              {menuItems.map((item, index) => (
                <button
                  key={item.id}
                  ref={(el) => {
                    if (el) navItemsRef.current[index] = el;
                  }}
                  className={`nav-item ${activeItem === item.id ? 'active' : ''}`}
                  onClick={() => handleItemClick(item)}
                >
                  <span className="nav-icon">{item.icon}</span>
                  <span className="nav-label">{item.label}</span>
                </button>
              ))}
            </nav>
          )}

          {/* Bottom Section */}
          <div ref={bottomSectionRef} className="sidebar-bottom">
            <div className="bottom-actions">
              {isAuthenticated ? (
                <>
                  <button className="action-btn user-info-btn" title={`用户: ${userPhone}`}>
                    <span className="action-icon">
                      <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
                        <g>
                          <path data-follow-fill="currentColor" d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"></path>
                        </g>
                      </svg>
                    </span>
                    <span className="user-phone-display">{userPhone?.slice(-4)}</span>
                  </button>
                  
                  <button className="action-btn" onClick={logout} title="退出登录">
                    <span className="action-icon">
                      <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
                        <g>
                          <path data-follow-fill="currentColor" d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                        </g>
                      </svg>
                    </span>
                  </button>
                </>
              ) : (
                <button className="action-btn" onClick={() => setShowLoginModal(true)} title="登录">
                  <span className="action-icon">
                    <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
                      <g>
                        <path data-follow-fill="currentColor" d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"></path>
                      </g>
                    </svg>
                  </span>
                </button>
              )}
              
              <button className="action-btn" title="设置">
                <span className="action-icon">
                  <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg">
                    <g>
                      <path data-follow-fill="currentColor" d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" stroke="currentColor" strokeWidth="2"/>
                      <path data-follow-fill="currentColor" d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1 1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1Z" stroke="currentColor" strokeWidth="2"/>
                    </g>
                  </svg>
                </span>
              </button>
            </div>
          </div>
        </div>
      </aside>

      {/* Mobile Dropdown Menu */}
      {isMobile && (
        <div 
          ref={dropdownRef}
          className={`mobile-dropdown ${isDropdownOpen ? 'open' : ''}`}
        >
          <div className="dropdown-content">
            {menuItems.map((item) => (
              <button
                key={item.id}
                className={`dropdown-item ${activeItem === item.id ? 'active' : ''}`}
                onClick={() => handleItemClick(item)}
              >
                <span className="dropdown-icon">{item.icon}</span>
                <span className="dropdown-label">{item.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </>
  );
};

export default Sidebar;
